// StandardSearchServlet.java
package com.medical.standard.controller.search;

import entity.Standard;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/standardSearch")
public class StandardSearchServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        String standardCode = request.getParameter("standardCode");

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT id, standard_code, standard_name, english_name, " +
                    "reference_type, publish_date, implementation_date " +
                    "FROM standard WHERE standard_code LIKE ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + standardCode + "%");

            rs = pstmt.executeQuery();

            List<Standard> standardList = new ArrayList<>();
            while (rs.next()) {
                Standard standard = new Standard(
                        rs.getInt("id"),
                        rs.getString("standard_code"),
                        rs.getString("standard_name"),
                        rs.getString("english_name"),
                        rs.getString("reference_type"),
                        rs.getDate("publish_date"),
                        rs.getDate("implementation_date")
                );
                standardList.add(standard);
            }

            // 将结果转换为JSON格式返回
            StringBuilder json = new StringBuilder();
            json.append("{\"success\":true,\"data\":[");
            for (int i = 0; i < standardList.size(); i++) {
                Standard standard = standardList.get(i);
                json.append("{");
                json.append("\"id\":\"").append(standard.getId()).append("\",");
                json.append("\"standardCode\":\"").append(escapeJson(standard.getStandardCode())).append("\",");
                json.append("\"standardName\":\"").append(escapeJson(standard.getStandardName())).append("\"");
                json.append("}");
                if (i < standardList.size() - 1) {
                    json.append(",");
                }
            }
            json.append("]}");

            response.getWriter().write(json.toString());

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"success\":false,\"message\":\"检索失败\"}");
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
    }

    private String escapeJson(String str) {
        if (str == null) return "";
        return str.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}